package org.akomantoso.core.io.util;

import java.io.IOException;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

import org.akomantoso.core.data.Destination;
import org.akomantoso.core.data.ModificationTypeElement;
import org.akomantoso.core.data.Source;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;

/**
 * 
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 * 
 */
public final class ModificationTypeElementUtil {

	private ModificationTypeElementUtil() {
	}

	static final Map<String, Instantiator<ModificationTypeElement>> MAP;

	public static void read(Input in, List<ModificationTypeElement> elements) throws IOException {

		ModificationTypeElement element = null;
		final String localName = in.getLocalName();

		int eventType;
		
		while (true) {
			eventType = in.readNext();
			switch (eventType) {
			case InputConstants.START_ELEMENT:
				element = instantiate(in.getLocalName());
				if (element == null) {
					return;
				}
				elements.add(element);
				element.readExternal(in);
				break;
			case InputConstants.END_ELEMENT:
				if (localName == in.getLocalName()) {
					return;
				}
			}
		}
	}

	static ModificationTypeElement instantiate(String elementName) {
		final Instantiator<ModificationTypeElement> instatiator = MAP.get(elementName);
		if (instatiator == null) {
			// @see TextualMod.
			return null;
		}
		return instatiator.instantiate();
	}

	static {

		Map<String, Instantiator<ModificationTypeElement>> temp = new IdentityHashMap<String, Instantiator<ModificationTypeElement>>();
		 
		// source
		temp.put(Source.ELEMENT, new Instantiator<ModificationTypeElement>() {
			public Source instantiate() {
				return new Source();
			}
		});

		// destination
		temp.put(Destination.ELEMENT, new Instantiator<ModificationTypeElement>() {
			public Destination instantiate() {
				return new Destination();
			}
		});
		
		MAP = temp;

	}
}
